package com.siyoumi.service.elasticsearch;

import com.siyoumi.component.XSpringContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.exception.BaseExceptionHandler;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class EsApi {
    static public EsApi getBean() {
        return XSpringContext.getBean(EsApi.class);
    }

    protected String getApiUrl(String fix) {
        return XStr.format("{0}{1}", SysConfig.getIns().getConsole().getAddress(), fix);
    }

    private XReturn execute(String method, String url, Map<String, Object> json) {
        XHttpClient client = XHttpClient.getInstance();

        log.debug("post_data: {}", XJson.toJSONString(json));
        Map<String, String> headers = new HashMap<>();
        headers.put("token", SysConfig.getIns().getConsole().getLongToken());

        log.debug("headers: {}", headers);
        XReturn r;
        try {
            String returnStr;
            if (XHttpClient.METHOD_GET.equals(method)) {
                returnStr = client.get(url, headers);
            } else {
                returnStr = client.postJson(url, headers, json);
            }
            r = XReturn.parse(returnStr);
        } catch (Exception ex) {
            BaseExceptionHandler.printStackTrace(ex);
            r = EnumSys.API_ERROR.getR(ex.getMessage());
        }
        if (r.err()) {
            if (XStr.contains(r.getErrMsg(), "Connection refused")) {
                XValidator.err(r);
            }
        }

        return r;
    }


    /**
     * 分词测试
     *
     * @param json
     */
    public XReturn analyzerTest(Map<String, Object> json) {
        String apiUrl = getApiUrl("es/analyzer_test");
        return execute(XHttpClient.METHOD_POST, apiUrl, json);
    }

    /**
     * 获取文档
     */
    public XReturn docInfo(String index, String id) {
        String apiUrl = getApiUrl(XStr.format("es/doc_info/{0}/{1}", index, id));
        return execute(XHttpClient.METHOD_GET, apiUrl, null);
    }

    /**
     * 添加或者更新
     */
    public XReturn docUpdate(String index, String id, Map<String, Object> json) {
        String apiUrl = getApiUrl(XStr.format("es/doc_update/{0}/{1}", index, id));
        return execute(XHttpClient.METHOD_POST, apiUrl, json);
    }

    public XReturn docDelete(String index, String id) {
        String apiUrl = getApiUrl(XStr.format("es/doc_delete/{0}/{1}", index, id));
        return execute(XHttpClient.METHOD_GET, apiUrl, null);
    }


    /**
     * 搜索文档
     */
    public XReturn docSearch(String index, Map<String, Object> json) {
        String apiUrl = getApiUrl(XStr.format("es/doc_search/{0}", index));
        return execute(XHttpClient.METHOD_POST, apiUrl, json);
    }
}
